define [
	'jquery'
	'helper'
	'template'
	'lib/jquery.couch.js'
], ($, H) ->
	
	search = (e) ->
		ins = e.delegateTarget

		# Skip if there is no search term
		return false unless q = $('[name="search_term"]', ins).val()

		# Lower case the query key for couchdb and parse through PostalCode and
		# Phone format
		q.toLowerCase().isPostal().isPhone()

		# If the query is in format LASTNAME, FIRSTNAME.. remove the space
		# after the comma to match the indexing
		(q = q.replace(/[ ]/g, '') if q.charAt(i+1) is " " ) if (i = q.indexOf(',')) isnt 0

		$.publish "mb.query",
			search_term: q
			search_type: $('[name="search_type"]:checked', ins).val().toLowerCase()

		return false

	$.fn.mb_search = ->
		@on 'click', '[name="reset"]', =>
			$('[name="search_term"]', @).val('')
		@on 'click', 'input:submit', search
		@on 'change', '[name="search_type"]', search
	return
